package com.wsz.security.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wsz.security.pojo.Role;
import com.wsz.security.pojo.User;
import com.wsz.security.pojo.UserRole;
import com.wsz.security.service.RoleService;
import com.wsz.security.service.UserRoleService;
import com.wsz.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServerImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", s));

        if(user == null){
            throw new UsernameNotFoundException("该用户不存在");
        }

        List<UserRole> userRoles = userRoleService.list(new QueryWrapper<UserRole>().eq("uid", user.getId()).select("rid"));

        List<Integer> roleIds = new ArrayList<>();

        userRoles.forEach(userRole -> {
            roleIds.add(userRole.getRid());
        });

        List<Role> roles = roleService.list(new QueryWrapper<Role>().in("id", roleIds));

        user.setRoles(roles);

        return user;
    }
}
